#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <IPHlpApi.h>
#include <cstdio>
#include <string>

#pragma comment(lib, "ws2_32.lib")

#define DEFAULT_PORT "60000"
#define DEFAULT_BUFLEN 2048



int main(int argc, char **argv[])
{
	char imgPath[512]{0};
	GetModuleFileNameA(NULL, imgPath, 512);
	*(strrchr(imgPath, '\\') + 1) = 0;
	int temp = strlen(imgPath);
	imgPath[temp++] = '1';
	imgPath[temp++] = '.';
	imgPath[temp++] = 'j';
	imgPath[temp++] = 'p';
	imgPath[temp++] = 'g';
	imgPath[temp] = 0;



	WSADATA wsaData;
	int iResult;
	struct addrinfo *result = NULL, *ptr = NULL, hints;

	iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (iResult != 0){
		printf("WSAStartup failed: %ld\n", iResult);
		return 1;
	}

	ZeroMemory(&hints, sizeof(hints));
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	hints.ai_flags = AI_PASSIVE;

	iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
	if (iResult != 0){
		printf("WSAStartup failed: %ld\n", iResult);
		WSACleanup();
		return 1;
	}

	SOCKET ListenSocket = INVALID_SOCKET;

	ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);

	if (ListenSocket == INVALID_SOCKET){
		printf("Error at socket(): %ld\n", WSAGetLastError());
		freeaddrinfo(result);
		WSACleanup();
		return 1;
	}

	iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
	if (iResult == SOCKET_ERROR){
		printf("bind failed with error: %ld\n", WSAGetLastError());
		freeaddrinfo(result);
		closesocket(ListenSocket);
		WSACleanup();
		return 1;
	}

	freeaddrinfo(result);

	printf("Waiting to be connected.\n");

	if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR){
		printf("Listen failed with error: %ld\n", WSAGetLastError());
		closesocket(ListenSocket);
		WSACleanup();
		return 1;
	}


	SOCKET Clientsocket = INVALID_SOCKET;


	//FILE *fp;
	//if ((fp = fopen(imgPath, "w+")) == NULL) {
	//	printf("File cannot be opened/n");
	//	return 1;
	//}

	//char msg[5] = {0xff, 0xfd, 0x00, 0x02, 0xaa};
	//int i = 0;
	//fputc(*msg, fp);
	//fputc(*(msg + 1), fp);
	//fputc(*(msg + 2), fp);
	//fputc(*(msg + 3), fp);
	//fputc(*(msg + 4), fp);
	//fclose(fp);


	while (1){
		Clientsocket = accept(ListenSocket, NULL, NULL);
		if (Clientsocket == INVALID_SOCKET){
			printf("accept failed: %d\n", WSAGetLastError());
			closesocket(ListenSocket);
			WSACleanup();
			return 1;
		}
		else
		{
			printf("Connection start.");
		}

		FILE *fp;
		remove(imgPath);
		fp = fopen(imgPath, "wb");
		fclose(fp);

		char recvbuf[DEFAULT_BUFLEN];
		int recvbuflen = DEFAULT_BUFLEN;
		long cnt = 0;
		do
		{
			iResult = recv(Clientsocket, recvbuf, recvbuflen, 0);
			if (iResult > 0){
				cnt = 0;
				fp = fopen(imgPath, "ab");
				printf("Bytes received: %d\n", iResult);
				while (cnt < iResult){
					fputc(recvbuf[cnt++], fp);
				}
			fclose(fp);

				//if (iResult < 6){
				//	printf("12");
				//	if ((recvbuf[0] == 'S') && (recvbuf[1] == 'T') && (recvbuf[2] == 'A')\
								//		&& (recvbuf[3] == 'R') && (recvbuf[4] == 'T')){
				//		printf(imgPath);

				//		if ((fp = fopen(imgPath, "w+")) == NULL) {
				//			if (fclose(fp) == NULL){
				//				if ((fp = fopen(imgPath, "w+")) == NULL) {
				//					printf("file opened./n");
				//				}
				//				else{
				//					printf("file cannot be opened, press any key to quit./n");
				//					getchar();
				//					return 1;
				//				}
				//			}
				//			else{
				//				printf("file cannot be opened, press any key to quit./n");
				//				getchar();
				//				return 1;
				//			}
				//		}
				//		else{
				//			printf("file opened./n");
				//		}
				//	}
				//	else if ((recvbuf[0] == 'S') && (recvbuf[1] == 'T') && (recvbuf[2] == 'O')\
								//		&& (recvbuf[3] == 'P')){
				//		printf("image rcving finished.\n");
				//		fclose(fp);
				//	}
				//	else{ 
				//		unsigned long cnt = 0;
				//		while (cnt < iResult){
				//			fputc(recvbuf[cnt++], fp);
				//		}
				//	}
				//}
				//else{
				//	unsigned long cnt = 0;
				//	while (cnt < iResult){
				//		fputc(recvbuf[cnt++], fp);
				//	}
				//}
			}
			else if (iResult == 0){
				printf("Connection closing...\n");
			}
			else{
				printf("recv failed: %d\n", WSAGetLastError());
				closesocket(Clientsocket);
				WSACleanup();
				return 1;
			}
		} while (iResult > 0);
	}
	iResult = shutdown(Clientsocket, SD_SEND);
	if (iResult == SOCKET_ERROR){
		printf("server shutdown failed %ld\n", WSAGetLastError());
		closesocket(Clientsocket);
		WSACleanup();
		return 1;
	}
	closesocket(Clientsocket);
	WSACleanup();

	return 0;
}